package com.doushu.websocket.common.utils;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.CookieStore;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.AbstractHttpMessage;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public final class HttpUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(HttpUtil.class);

    /**
     * 设置请求参数，模拟浏览器请求
     *
     * @param message
     */
    public static void headerWrapper(AbstractHttpMessage message) {
        message.setHeader("user-agent",
                "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36");
        message.setHeader("accept", "*/*");
        message.setHeader("accept-language", "zh-CN");
        message.setHeader("Accept-Encoding", "gzip, deflate");
    }

    /**
     * 创建closeableHttpClient对象
     *
     * @param isSSL
     * @param cookies
     * @return
     */
    public static CloseableHttpClient createHttpClient(boolean isSSL, CookieStore cookies) {
        if (isSSL) {
            SSLContext sslContext = null;
            try {
                //信任所有
                sslContext = new SSLContextBuilder().loadTrustMaterial(null, (chain, authType) -> true).build();
            } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
                e.printStackTrace();
            }
            if (null != sslContext) {
                SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);
                return HttpClients.custom().setSSLSocketFactory(sslsf).setDefaultCookieStore(cookies).build();
            } else {
                return HttpClients.custom().setDefaultCookieStore(cookies).build();
            }
        } else {
            return HttpClients.custom().setDefaultCookieStore(cookies).build();
        }
    }

    /**
     * ssl post 请求封装
     *
     * @param url
     * @param params
     * @return
     */
    public static String client(String url, Map<String, String> params) {
        try (CloseableHttpClient httpClient = HttpUtil.createHttpClient(true, new BasicCookieStore())) {
            List<NameValuePair> list = new ArrayList<>();
            HttpPost httpPost = new HttpPost(url);
            HttpUtil.headerWrapper(httpPost);
            httpPost.setHeader("accept-Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
            for (Map.Entry<String, String> entry : params.entrySet()) {
                list.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }
            httpPost.setEntity(new UrlEncodedFormEntity(list, "UTF-8"));
            HttpResponse httpresponse = httpClient.execute(httpPost);
            if (httpresponse.getStatusLine().getStatusCode() == 200) {
                HttpEntity entity = httpresponse.getEntity();
                String json = EntityUtils.toString(entity);
                LOGGER.info("请求：{}，参数：{}，返回：{}", url, params, json);
                return json;
            }
        } catch (IOException e) {
            LOGGER.error("发送请求：{}失败,参数：{}", url, params, e);
        }
        return null;
    }
}
